var app = getApp();
var api = require('../../utils/util.js').default;
Page({
  data: {
    // 滑动栏组件
    TabCur: 0,
    scrollLeft: 0,
    switchState: ['用户', '骑手'],
    selected: 0, // 0-用户,1-骑手

    // 页面数据
    pho_num: null,
    user_name: null,
    school_num: null,
    is_visitor: true,
    deliverList: [],
    currentDeliverList: {},
    is_rider: 0,
    is_working: false,
    realnametag: "未实名",
    ridertag: "未成为骑手",

    // 订单渲染相关数据
    //             000       003       001       002
    order_type: ['匹配中', '待接受', '配送中', '已送达'], // no use
    case0: [], // 000,003--<待配送
    case1: [], // 001--<配送中
    case2: [], // 002--<已送达
    case3: [], // ???--<退款
  },


  // 用户订单获取(更新case数组)
  getUserOrder: function () {
    var data = {
      openid: app.globalData.openid,
    }
    this.clearOrder();
    api.getUserOrder(data).then(res => {
      console.log("用户订单获取：")
      console.log(res.data.data)
      wx.setStorageSync('user_order', res.data.data);
      this.classifyOrder();
      this.consoleOrder();
    })
  },

  // 订单调试
  consoleOrder: function () {
    console.log("case0：待配送")
    console.log(this.data.case0)
    console.log("case1：配送中")
    console.log(this.data.case1)
    console.log("case2：已完成")
    console.log(this.data.case2)
    console.log("case3：退款")
    console.log(this.data.case3)
  },

  // 清空订单
  clearOrder: function () {
    this.setData({
      case0: [],
      case1: [],
      case2: [],
      case3: []
    })
  },

  // 订单分类
  classifyOrder: function () {
    var arr = wx.getStorageSync('user_order');
    for (let i = arr.length - 1; i >= 0; i--) {
      var singleData = arr[i];
      switch (singleData.sever_type) { //服务类型
        case "1":
          singleData.sever_type = "快递代拿";
          break;
        case "2":
          singleData.sever_type = "外卖代拿";
          break;
        case "3":
          singleData.sever_type = "食堂代拿";
          break;
        case "4":
          singleData.sever_type = "超市代买";
          break;
        default:
          singleData.sever_type = "未知类型";
      }

      switch (singleData.status) { //接单情况
        case "000":
          singleData.status_show = "匹配中";
          break;
        case "001":
          singleData.status_show = "配送中";
          break;
        case "002":
          singleData.status_show = "已送达";
          break;
        case "003":
          singleData.status_show = "待接受";
          break;
        case "004":
          singleData.status_show = "退款";
          break;
        case "005":
          singleData.status_show = "退款中";
          break;
        case "006":
          singleData.status_show = "退款成功";
          break;
        default:
          singleData.status_show = "未知状态";
      }

      if (singleData.torider.length < 20) { //判断是否有骑手
        singleData.nickName = "【暂无骑手接单】";
      }
      var singleObject = {
        tocustomer: singleData.tocustomer, //客户名
        sever_type: singleData.sever_type, //服务类型选择
        meet_place: singleData.meet_place, //交接地点
        unit_price: singleData.unit_price, //单价
        cus_details: singleData.cus_details, //客户的备注信息
        upload_time: singleData.upload_time, //订单提交时间
        torider: singleData.torider, //选择骑手
        status: singleData.status,
        status_show: singleData.status_show,
        img_src:singleData.head,
        rider_name:singleData.nickName,
      };
      switch (singleData.status) { //接单情况
        case "000": //匹配中 
        case "003": //待接受

          this.setData({
            case0: this.data.case0.concat(singleObject)
          });
          break;
        case "001": //配送中

          this.setData({
            case1: this.data.case1.concat(singleObject)
          });
          break;
        case "002": //已送达

          this.setData({
            case2: this.data.case2.concat(singleObject)
          });
          break;
        case "004": //可退款
        case "005": //已退款

          this.setData({
            case3: this.data.case3.concat(singleObject)
          });
          break;
        default:
          console.log("归类出错");
      }
    }
  },

  // 骑手订单确认
  riderOrderConfirm:function(){
    wx.showModal({
      title: '确认送达',
      content: '请在送达订单后，\n让客户在<配送中>页面确认收货',
      showCancel: false,
      confirmText: '知道啦',
      confirmColor: '#3CC51F',
    });
  },

  // 下拉刷新组件
  onPullDownRefresh: function () {
    this.updataUserinfo();
    setTimeout(function () {
      wx.stopPullDownRefresh();
    }, 2000);
  },

  // 更新全局用户数据
  updataUserinfo:function(){
    var that = this
    wx.login({
      success(res) {
        if (res.code) {
          var data = {
            code: res.code
          }
          api.app_login(data).then(res => {
            app.globalData.is_visitor = res.data.is_visitor;
            app.globalData.is_defined = res.data.is_defined;
            app.globalData.is_rider = res.data.is_rider;
            app.globalData.openid = res.data.openid;
            app.globalData.sessionkey = res.data.session_key;
            app.globalData.school_num = res.data.school_num;
            var name = res.data.nickname;
            if (name.length > 7) {
              app.globalData.user_name = name.substr(res.data.nickname, 6) + '…'
            } else {
              app.globalData.user_name = name;
            }
            app.globalData.user_img = res.data.img_src;
            app.globalData.user_pho = res.data.pho_num;
            console.log("globaldata：")
            console.log(app.globalData);
            that.onShow();
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  },

  // 页面渲染+用户订单更新
  onShow: function () {
    console.log("onshow")
    this.tagInitialize();
    this.getUserOrder();
    this.setData({
      user_name: app.globalData.user_name,
      is_visitor: app.globalData.is_visitor,
      imgUrl: app.globalData.user_img,
      is_rider: app.globalData.is_rider
    })
  },

  // 未登录提示
  unloginTap: function () {
    wx.showToast({
      title: '请先登录',
      icon: 'loading',
      duration: 500,
      mask: false,
    });
  },

  // tag初始化
  tagInitialize: function () {
    if (app.globalData.is_defined) {
      this.setData({
        realnametag: "已实名"
      })
    }
    if (app.globalData.is_rider == 1) {
      this.setData({
        ridertag: "正式骑手"
      })
    } else if (app.globalData.is_rider == 2) {
      this.setData({
        ridertag: "骑手审核中"
      })
    }
  },

  // 骑手用户滑动栏组件
  tabSelect(e) {
    if (e.target.dataset.id != this.data.selected) {
      var id = e.target.dataset.id
      if (e.target.dataset.id == 1) {
        console.log("获取骑手的订单列表：")
        this.getRiderOrder();
        this.getRiderStatus();
      }
      this.setData({
        selected: e.target.dataset.id,
        TabCur: e.currentTarget.dataset.id,
        scrollLeft: (e.currentTarget.dataset.id - 1) * 60
      })
    } else {
      console.log("乱动nm")
    }
  },

  // 获取骑手配送订单接口
  getRiderOrder: function () {
    this.setData({
      deliverList: [],
    })
    var data = {
      torider: app.globalData.openid,
    }
    api.getRiderOrder(data).then(result=>{
      console.log("骑手订单接口：")
        console.log(result.data);
        var arr = result.data; //绑定数据到Data.gotmsg
        var dataList = new Array();
        dataList = arr.data; //切割返回的数据成为多条订单
        console.log(dataList.length)
        for (let i = 0; i < dataList.length; i++) {
          var singleData = new Array();
          if (dataList[i]) {
            singleData = dataList[i];
            switch (singleData.sever_type) {
              case "1":
                singleData.sever_type = "快递代拿";
                break;
              case "2":
                singleData.sever_type = "外卖代拿";
                break;
              case "3":
                singleData.sever_type = "食堂代拿";
                break;
              case "4":
                singleData.sever_type = "超市代买";
                break;
              default:
                singleData.sever_type = "无效服务";
            }
            let singleObject = {};
            singleObject = {
              tocustomer: singleData.tocustomer, //客户名
              sever_type: singleData.sever_type, //服务类型选择
              meet_place: singleData.meet_place, //交接地点
              unit_price: singleData.unit_price, //单价
              cus_details: singleData.cus_details, //客户的备注信息
              upload_time: singleData.upload_time, //订单提交时间
              choose_rider: singleData.choose_rider, //选择骑手
              status: singleData.status,
              shoppingId: singleData.id
            }
            console.log(singleObject);
            this.setData({
              deliverList: this.data.deliverList.concat(singleObject)
            });
          }
        }
        console.log(this.data.deliverList);
    })
  },

  // 获取用户头像和昵称、注册时间
  login: function () {
    var self = this
    wx.getUserInfo({
      success: function (res) {
        var regtime = api.formatTime(new Date());
        var data = {
          openid: app.globalData.openid,
          userNick: res.userInfo.nickName,
          avatarUrl: res.userInfo.avatarUrl,
          reg_time: regtime,
        }
        api.login(data).then(res => {
          console.log(res.data)
          app.globalData.user_name = res.data.user_name
          app.globalData.user_img = res.data.user_img
          app.globalData.is_visitor = res.data.is_visitor
          app.globalData.is_defined = res.data.is_defined
          app.globalData.is_rider = res.data.is_rider
          app.globalData.school_num = res.data.school_num
          app.globalData.pho_num = res.data.pho_num
          self.setData({
            user_name: app.globalData.user_name,
            imgUrl: app.globalData.user_img,
            is_visitor: app.globalData.is_visitor,
          })
          self.tagInitialize();
          wx.showToast({
            title: '登录成功',
            icon: "success",
            duration: 800
          })
        })
      },
      fail: function (res) {
        console.log("用户数据获取失败")
      },
    }) //wx.getuserinfo
  },

  // 用户子订单列表
  gotoUserOrdercheck: function (e) {
    var type = e.currentTarget.dataset.type
    if (!app.globalData.is_visitor) {
      wx.navigateTo({
        url: '../user_Ordercheck/user_Ordercheck?type=' + type
      })
    } else {
      wx.showToast({
        title: '请登录',
        icon: "loading",
        duration: 700
      })
    }
  },

  // 检查订单页面
  gotoOrderCheck: function () {
    if (!app.globalData.is_visitor) {
      wx.navigateTo({
        url: '../user_historyOrder/user_historyOrder'
      })
    } else {
      wx.showToast({
        title: '请登录',
        icon: "loading",
        duration: 700
      })
    }
  },

  // 修改信息页面
  gotoCustomerInfo: function () {
    if(app.globalData.is_rider=='1'||app.globalData.is_rider=='2'){
      wx.showToast({
        title: '已完成认证',
        icon: 'success',
        duration: 1000,
      });
        
    }else{
      wx.navigateTo({
        url: '../user_fillUserinfo/user_fillUserinfo'
      })
    }
   
  },

  // 骑手工作状态查询接口
  getRiderStatus:function(){
    var data = {
      openid:app.globalData.openid
    }
    api.getRiderStatus(data).then(result=>{
      console.log(result)
      this.setData({
        is_working:result.data.data.is_active
      })
    })
  },

  //改变骑手工作状态
  setRiderStatus: function (e) {
    console.log('state：'+e.detail.value)
    var data={
      is_active: e.detail.value ? 1 : 0,
      openid: app.globalData.openid
    }
    api.setRiderStatus(data).then(result=>{
        console.log(result)
        if(result.data == 1){
          wx.showToast({
            title: '切换成功~',
            duration: 1000,
          });
          this.setData({
            is_working: e.detail.value
          });
        }else{
          wx.showToast({
            title: '网络错误',
            icon: 'loading',
            duration: 1000,
          });
          this.setData({
            is_working: !e.detail.value
          });
        }
    })
  },

  // 骑手认证提示
  aboutRider:function(){
    wx.showModal({
      title: '骑手认证',
      content: '请在<资格认证>页面先完成实名认证后，进入骑手申请页面',
      showCancel: false,
      confirmText: '确定',
      confirmColor: '#3CC51F',
    });
  }

})